<template>
    <div class="chart-container">
      <div ref="pieChartRef" class="pie-chart" :style="{ width: width, height: height }"></div>
      <div ref="lineChartRef" class="line-chart" :style="{ width: width, height: '250px' }"></div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted, watch, defineExpose } from 'vue'
  import * as echarts from 'echarts'

  const emit = defineEmits(['getMoreLastData'])
  
  const props = defineProps({
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    title: {
      type: String,
      default: ''
    },
    xAxisData: {
      type: Array,
      default: () => []
    },
    seriesData: {
      type: Array,
      default: () => []
    },
    legend: {
      type: Array,
      default: () => []
    },
    colors: {
      type: Array,
      default: () => []
    }
  })
  
  const lineChartRef = ref(null)
  const pieChartRef = ref(null)
  let lineChartInstance = null
  let pieChartInstance = null
  const lastStart = ref(0);
  const lastEnd = ref(0);
  
// 初始化折线图
const initLineChart = () => {
  if (!lineChartRef.value) return

  lineChartInstance = echarts.init(lineChartRef.value)
  
  const rootStyle = getComputedStyle(document.documentElement)
  const menuTextColor = rootStyle.getPropertyValue('--default-color').trim()

  const option = {
    title: {
      text: props.title,
      left: 'left',
      top: '10',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal',
        color: menuTextColor // 设置标题颜色
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: props.legend,
      textStyle: {
        fontSize: 14,
        color: menuTextColor // 设置图例颜色
      },
      bottom: '0',
      left: '46%',
    },
    grid: {
      left: '10%',
      right: '10%',
      top: '20%',
      bottom: '12%', // 为滚动条留出空间
      containLabel: true,
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        fontSize: 12, // 调整 y 轴标签字体大小
        margin: 10,
        color: menuTextColor // 设置 Y 轴标签颜色
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.xAxisData,
      axisLabel: {
        interval: 0,
        rotate: 45,
        margin: 10,
        fontSize: 12,
        width: 120,
        padding: [5, 0, 0, 0],
        color: menuTextColor // 设置 X 轴标签颜色
      },
      axisTick: {
        show: false,
        alignWithLabel: true,
        interval: 0
      },
      axisLine: {
        lineStyle: {
          width: 1,
          color: menuTextColor // 设置 X 轴线颜色
        }
      }
    },
    // 移除重复的 yAxis 定义
    // yAxis: {
    //   type: 'value'
    // },
    dataZoom: [
      {
        type: 'slider',
        show: false,
        xAxisIndex: [0],
        start: 80,
        end: 100,
        bottom: '2%',
        handleSize: 10,
        handleStyle: {
            color: '#DCE2E8' // 滑动条的手柄颜色
        },
        value: [0, 20],
        minValueSpan: 10,
        maxValueSpan: 20,
        step: 1,
        zoomLock: true
      },
      {
        type: 'inside',
        xAxisIndex: [0],
        start: 80,
        end: 100,
        minValueSpan: 20,
        maxValueSpan: 20,
        step: 1,
        zoomLock: true
      }
    ],

    series: props.seriesData.map((data, index) => ({
      name: props.legend[index],
      type: 'line',
      data: data,
      smooth: true,
      areaStyle: {
        opacity: 0.1
      },
      itemStyle: {
        color: props.colors[index % props.colors.length]
      },
      lineStyle: {
        color: props.colors[index % props.colors.length]
      }
    }))
  }
  
  lineChartInstance.setOption(option)

  // updateAxisPointer 移入
  lineChartInstance.on('click', function (event) {
    // if (event.axesInfo.length) {
      updatePieData(event.dataIndex)
    // }
  });

  // 添加数据缩放事件
  lineChartInstance.on('datazoom', function (params) {
    if (params.batch) {
      const start = params.batch[0].start;
      const end = params.batch[0].end;
      const total = props.xAxisData.length;
      const startIndex = Math.floor(start / 100 * total);
      const endIndex = Math.floor(end / 100 * total);

      // 判断是否滑动到最右侧（即“右滑到底”）
      if (end === 100) {
        // console.log('ECharts dataZoom has scrolled to the right end!');
        // 在这里可以触发加载更多数据的逻辑
      }

      if (start === 0) {
        // console.log('ECharts dataZoom has scrolled to the left end!');
        // 在这里可以触发加载更早数据的逻辑
        emit('getMoreLastData')
      }

      // 更新上一次的start和end值
      lastStart.value = start;
      lastEnd.value = end;

      updatePieData(startIndex);
    }
  });
}

  
  // 初始化饼图
  const initPieChart = () => {
    if (!pieChartRef.value) return
  
    pieChartInstance = echarts.init(pieChartRef.value)
    
    const pieData = props.seriesData.map((data, index) => ({
      name: props.legend[index],
      value: data[0] || 0
    }))

    // 获取主题文本颜色
    const rootStyle = getComputedStyle(document.documentElement);
    const menuTextColor = rootStyle.getPropertyValue('--default-color').trim();
    let option = pieChartInstance.getOption()

    if(!option) {
      option = {
        // tooltip: {
        //   trigger: 'item',
        //   formatter: '{a} <br/>{b}: {c} ({d}%)'
        // },
        series: [{
          type: 'pie',
          radius: ['40%', '60%'],
          center: ['50%', '50%'],
          emphasis: {
            focus: 'self'
          },
          label: {
            show: true,
            position: 'outside',
            formatter: '{b|{b}}\n{per|{d}%}',
            rich: {
              b: {
                fontSize: 14,
                lineHeight: 33,
                textShadow: 'none',
                color: menuTextColor // 应用主题色
              },
              per: {
                padding: [2, 4],
                borderRadius: 2,
                textShadow: 'none',
                backgroundColor: 'transparent',
                color: menuTextColor // 应用主题色
              }
            }
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 10
          },
          data: pieData
        }]
      }
    }
    option.series[0].label.rich.b.color = menuTextColor
    option.series[0].label.rich.per.color = menuTextColor
    
    pieChartInstance.setOption(option)
  }

  // 更新饼图数据
  const updatePieData = (dataIndex) => {
    return
    if (pieChartInstance) {
      const values = props.seriesData.map((data, index) => {
        return {
            name: props.legend[index],
            value: data[dataIndex] || 0
        }
      })
      
      const option = pieChartInstance.getOption()

      option.series[0].data = values.filter(item => item.name)
      pieChartInstance.setOption(option)
    }
  }

  const changePieData = (values) => {
    if(!pieChartInstance) {
      setTimeout(() => {
        changePieData(values)
      }, 500)
      return
    }

    const option = pieChartInstance.getOption()
    option.series[0].data = values
    pieChartInstance.setOption(option)
  }
  
  onMounted(() => {
    initLineChart()
    initPieChart()
    
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      if (lineChartInstance) lineChartInstance.resize()
      if (pieChartInstance) pieChartInstance.resize()
    })

    // 监听主题变化
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
          // 当html元素的class属性变化时，重新初始化图表以更新颜色
          initPieChart();
          initLineChart(); // 添加这行以重新初始化折线图
        }
      });
    });

    observer.observe(document.documentElement, { attributes: true });

    onUnmounted(() => {
      observer.disconnect();
    });
  })
  onUnmounted(() => {
  if (lineChartInstance) {
    lineChartInstance.dispose()
    lineChartInstance = null
  }
  if (pieChartInstance) {
    pieChartInstance.dispose()
    pieChartInstance = null
  }
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', () => {
    if (lineChartInstance) lineChartInstance.resize()
    if (pieChartInstance) pieChartInstance.resize()
  })
})

// 监听数据变化
watch(
  () => [props.xAxisData, props.seriesData, props.legend, props.title, props.colors],
  () => {
    if (lineChartInstance) {
      initLineChart()
    }
    if (pieChartInstance) {
      initPieChart()
    }
  },
  { 
    deep: true,
    immediate: true
  }
)

defineExpose({
  changePieData
})
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0px;
  padding: 10px;
}

.line-chart {
  flex: 1;
  min-width: 0;
}

.pie-chart {
  width: 100%;
  min-width: 0;
  height: 100px;
}

/* 防止图表被滚动条遮挡 */
.chart-container {
  overflow: hidden;
}
</style>
